﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WCrawlerLib;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
using PhotobucketNet;

namespace WCrawler.Controls
{
    public partial class ucPost : System.Web.UI.UserControl
    {
        private int _indexPost = 0; 

        protected void ucTreeViewTopic_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ucTreeViewTopic.SelectedNode != null)
            {
                Session["TopicIds"] = ucTreeViewTopic.GetTopics(ucTreeViewTopic.SelectedNode);
                gridViewPosts.DataBind();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                //Remove session before check
                Session["PostCheckLinks"] = null;
                Session["CurrentPost"] = null;
                //Session["IsNewPostDetails"] = null;

                gridViewPosts.SelectedIndex = 0;
                gridViewPosts.DataBind();
                
                //Show exactly post with paging
                if (!string.IsNullOrEmpty(Request.QueryString["PostId"]))
                {
                    object postId = Request.QueryString["PostId"];
                    for (int i = 0; i < gridViewPosts.PageCount; i++)
                    {
                        gridViewPosts.PageIndex += i;
                        gridViewPosts.SelectedIndex = gridViewPosts.DataKeys.IndexOf("PostId", postId);
                        if (gridViewPosts.SelectedIndex != -1)
                            break;
                        gridViewPosts.DataBind();
                    }
                }
                Session["PostId"] = gridViewPosts.SelectedDataKey["PostId"];
                GridView gridViewForums = (GridView)ucHostFile.FindControl("gridViewFilePosts");
                gridViewForums.Columns[1].Visible = false;
                //gridViewForums.Columns[2].Visible = false;
                /*CommandField cmdField = (CommandField)gridViewForums.Columns[0];
                cmdField.ShowEditButton = false;
                cmdField.ShowDeleteButton = false;*/
            }
        }

        public event EventHandler GridViewPosts_SelectedIndexChanged;
        protected void gridViewPosts_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["PostId"] = gridViewPosts.SelectedDataKey["PostId"];
            if (GridViewPosts_SelectedIndexChanged != null)
                GridViewPosts_SelectedIndexChanged(sender, e);
            BindingControls();
            
            AjaxControlToolkit.TabContainer objTabControl =  (AjaxControlToolkit.TabContainer)this.FindControl("TabContainerPost");
            Button linkSelect = (Button)objTabControl.Tabs[0].FindControl("btnSelectedIndex");
            linkSelect.Text = "linkSelect('row" + gridViewPosts.SelectedIndex.ToString() + "\')";
        }

        public void BindingControls()
        {
            detailsViewPost.DataBind();

            //Controls in Tabcontainer
            detailsViewPostDetails.DataBind();
            ucHostFile.GridViewFilePosts_DataBind();
            ucImage.GridViewPostImages_DataBind();
            ucSearchIMDB.SearchIMDB_DataBind();
            ucSearchHostFiles.SearchHostFiles_DataBind();
        }

        protected void PostDetailsLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (gridViewPosts.SelectedDataKey != null)
            {
                PostDetail objPostDetails = new PostDetail();
                int postId = (int)gridViewPosts.SelectedDataKey["PostId"];
                IQueryable<PostDetail> query = objPostDetails.GetAll().WherePost(postId.ToString());

                if (query.Count() > 0)
                {
                    if (detailsViewPostDetails.CurrentMode == DetailsViewMode.Insert)
                        detailsViewPostDetails.ChangeMode(DetailsViewMode.ReadOnly);
                }
                else
                {
                    detailsViewPostDetails.ChangeMode(DetailsViewMode.Insert);
                }

                e.Result = query;
            }
            else
            {
            }
        }

        public GridView GetGridViewControl()
        {
            AjaxControlToolkit.TabContainer objTabControl =  (AjaxControlToolkit.TabContainer)this.FindControl("TabContainerPost");
            return (GridView)objTabControl.Tabs[0].FindControl("gridViewPosts");
        }

        public Post GetCurrentPost()
        {
            Post objPost = new Post();
            //if (Session["CurrentPost"] != null)
            //    objPost = (Post)Session["CurrentPost"];
            //else
            //{
                if (gridViewPosts.SelectedDataKey != null)
                {
                    objPost = objPost.GetPost((int)gridViewPosts.SelectedDataKey["PostId"]);
              //      Session["CurrentPost"] = objPost;
                }
            //}
            return objPost;
        }

        protected void Post2LinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (gridViewPosts.Rows.Count == 0)
            {
                detailsViewPost.ChangeMode(DetailsViewMode.Insert);
                TabContainerPost.Enabled = false;
            }
            else
            {
                TabContainerPost.Enabled = true;
                if (detailsViewPost.CurrentMode == DetailsViewMode.Insert)
                    detailsViewPost.ChangeMode(DetailsViewMode.ReadOnly);
                if (gridViewPosts.SelectedDataKey != null)
                {
                    int postId = (int)gridViewPosts.SelectedDataKey["PostId"];
                    Post objPost = new Post();
                    e.Result = objPost.GetPost(postId);
                }
            }

        }

        protected void detailsViewPost_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            gridViewPosts.SelectedIndex = gridViewPosts.Rows.Count - 1;
            gridViewPosts.DataBind();
        }

        protected void detailsViewPost_ItemDeleted(object sender, DetailsViewDeletedEventArgs e)
        {
            gridViewPosts.DataBind();
        }

        protected void detailsViewPostDetails_DataBound(object sender, EventArgs e)
        {
            if (detailsViewPostDetails.CurrentMode == DetailsViewMode.Insert)
            {
                Post objPost = new Post();
                if (gridViewPosts.SelectedDataKey != null)
                {
                    objPost = objPost.GetPost((int)gridViewPosts.SelectedDataKey["PostId"]);

                    //language
                    DropDownList LanguageDropDownList = (DropDownList)detailsViewPostDetails.FindControl("LanguageDropDownList");
                    LanguageDropDownList.SelectedValue = ((int)enumLanguage.English).ToString();
                    //post title
                    TextBox txtPostTitle = (TextBox)detailsViewPostDetails.FindControl("txtPostTitle");
                    txtPostTitle.Text = objPost.PostTitle;
                    //create on
                    TextBox txtCreateOn = (TextBox)detailsViewPostDetails.FindControl("txtCreateOn");
                    txtCreateOn.Text = DateTime.Now.ToString();
                    //update on
                    TextBox txtUpdateOn = (TextBox)detailsViewPostDetails.FindControl("txtUpdateOn");
                    txtUpdateOn.Text = DateTime.Now.ToString();
                }
            }
            else //if (detailsViewPostDetails.CurrentMode == DetailsViewMode.Edit)
            {
                TextBox txtUpdateOn = (TextBox)detailsViewPostDetails.FindControl("txtUpdateOn");
                if (txtUpdateOn!=null)
                    txtUpdateOn.Text = DateTime.Now.ToString();
            }
        }

        protected void detailsViewPostDetails_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            if (e.Values["PostId"] == null)
            {
                e.Values["PostId"] = (int)gridViewPosts.SelectedDataKey["PostId"];
            }
        }

        protected void btnHtmlCode_Click(object sender, EventArgs e)
        {
            PostDetail objPostDetail = new PostDetail();
            objPostDetail = objPostDetail.GetPostDetail((int)detailsViewPostDetails.SelectedValue);
            txtHmtlCode.Text = objPostDetail.GetFullHtmlContent((enumForumType)enumForumType.vBulletin, false, false);
            txtHmtlCode.Rows = 20;
            lblMessage.Text = "";
            mdlPopup.Show();
        }
        
        protected void btnPhpBB2_Click(object sender, EventArgs e)
        {
            PostDetail objPostDetail = new PostDetail();
            objPostDetail = objPostDetail.GetPostDetail((int)detailsViewPostDetails.SelectedValue);
            txtHmtlCode.Text = objPostDetail.GetFullHtmlContent(enumForumType.phpBB2, false, false);
            txtHmtlCode.Rows = 20;
            lblMessage.Text = "";
            mdlPopup.Show();
        }

        protected void btnPhpBB3_Click(object sender, EventArgs e)
        {
            PostDetail objPostDetail = new PostDetail();
            objPostDetail = objPostDetail.GetPostDetail((int)detailsViewPostDetails.SelectedValue);
            txtHmtlCode.Text = objPostDetail.GetFullHtmlContent(enumForumType.phpBB3, false, false);
            txtHmtlCode.Rows = 20;
            lblMessage.Text = "";
            mdlPopup.Show();
        } 

        protected void btnIPB_Click(object sender, EventArgs e)
        {
            PostDetail objPostDetail = new PostDetail();
            objPostDetail = objPostDetail.GetPostDetail((int)detailsViewPostDetails.SelectedValue);
            txtHmtlCode.Text = objPostDetail.GetFullHtmlContent(enumForumType.IPB, false, false);
            txtHmtlCode.Rows = 20;
            lblMessage.Text = "";
            mdlPopup.Show();
        }

        //protected void TabContainerPost_ActiveTabChanged(object sender, EventArgs e)
        //{
        //    //int tab1 = TabContainerPost.ActiveTabIndex;
        //}

        protected void PostLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            if (ucTreeViewTopic.SelectedNode != null)
            {
                Session["TopicIds"] = ucTreeViewTopic.GetTopics(ucTreeViewTopic.SelectedNode);

                Post objPost = new Post();
                IQueryable<Post> query = objPost.GetAll().WhereTopic(Session["TopicIds"].ToString())
                                                         .IsApproved(dropDownListIsApproved.SelectedIndex);
                e.Result = query;
                if (query.Count() > 0)
                {
                    gridViewPosts.SelectedIndex = 0;
                }
                else
                {
                    Session["CurrentPost"] = null;
                    //gridViewPosts.SelectedIndex = -1;
                }
                BindingControls();
            }
        }

        protected void gridViewPosts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
                _indexPost = gridViewPosts.PageSize * gridViewPosts.PageIndex + 1;
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //IHTMLElement::scrollIntoView
                string rowId = "row"+e.Row.RowIndex;
                e.Row.Attributes.Add("id", rowId);
                //Create order numbers
                ((Label)e.Row.FindControl("lblNum")).Text = (_indexPost++).ToString();
                //Button linkSelect = (Button)e.Row.FindControl("linkSelect");
                //linkSelect.Attributes.Add("onclick", "linkSelect('" + rowId + "')");
            }
        }

        protected void ImageLinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            ImagePost objImagePost = new ImagePost();
            int postId = -1;
            if (gridViewPosts.SelectedDataKey != null)
                postId = (int)gridViewPosts.SelectedDataKey["PostId"];
            e.Result = objImagePost.GetImagesByPost(postId);
        }

        protected void detailsViewPost_DataBound(object sender, EventArgs e)
        {
            if (detailsViewPost.CurrentMode != DetailsViewMode.ReadOnly)
            {
                //create on
                TextBox txtCreateOn = (TextBox)detailsViewPost.FindControl("txtCreateOn");
                if (txtCreateOn.Text == "")
                    txtCreateOn.Text = DateTime.Now.ToString();
            }
        }

        protected void detailsViewPost_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
        {
            //ViewState["LastIndex"] = gridViewPosts.SelectedIndex;
            gridViewPosts.DataBind();
            //if (ViewState["LastIndex"] != null){
            //    gridViewPosts.Rows[(int)ViewState["LastIndex"]].Visible = true;
                
            //gridViewPosts.Rows[gridViewPosts.SelectedIndex].Visible = true; 
            //ViewState["LastIndex"] = gridViewPosts.SelectedIndex;
            //gridViewPosts.SelectedIndex = (int)Session["SelectedIndex"];
        }

        protected void detailsViewPost_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            //Session["SelectedIndex"] = gridViewPosts.SelectedIndex;
        }

        protected void LinkButton1_Command(object sender, CommandEventArgs e)
        {

        }

        protected void linkSelect_Command(object sender, CommandEventArgs e)
        {
            //Panel panel = (Panel)this.FindControl("linkSelect");
            //linkSelect.Attributes.Add("oncommand", "linkSelect('" + rowId + "')");
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void dropDownListIsApproved_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridViewPosts.DataBind();
        }

        protected void detailsViewPost_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
        {

        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gridViewPosts.Rows)
            {
                CheckBox chkBx = (CheckBox)row.FindControl("chkCheckItem");
                if (chkBx != null && chkBx.Checked)
                {
                    Post objForum = new Post();
                    objForum.SetApproved((int)gridViewPosts.DataKeys[row.RowIndex].Value, true);
                }
            }
            gridViewPosts.DataBind();
        }
    }
}